from django.shortcuts import render
from .models import *
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.db.models import Q
from django.core import serializers
from utils.jwt_auth import create_token,parse_payload
from decorators.jwt import auth_permission_required
from django.core.paginator import Paginator
import json
import hashlib


# Create your views here.
# 获取文章记录
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
def article_list(request):
    response = {}
    try:
        page = request.GET.get('page')
        int(page)
        articles = Article.objects.filter().order_by("-date_created")
        paginator = Paginator(articles, 6)
        article_list = paginator.page(page)
        response['list'] = json.loads(serializers.serialize("json",article_list,use_natural_foreign_keys=True))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = '到底了，没数据了'
        response['error_num'] = 1
    
    return JsonResponse(response)

# Create your views here.
# 获取指定分类文章记录
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
def article_list_cat(request):
    response = {}
    try:
        page = request.GET.get('page')
        int(page)
        category = request.GET.get('category')
        print(category)
        categoryId = Category.objects.get(name = category)
        articles = Article.objects.filter(category = categoryId).order_by("-date_created")
        paginator = Paginator(articles, 6)
        article_list = paginator.page(page)
        response['list'] = json.loads(serializers.serialize("json",article_list,use_natural_foreign_keys=True))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = '到底了，没数据了'
        response['error_num'] = 1
    
    return JsonResponse(response)

# 获取指定文章
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
def article(request):
    response = {}
    try:
        id = request.GET.get('id')
        articles = Article.objects.filter(pk = id)
        response['list'] = json.loads(serializers.serialize("json",articles,use_natural_foreign_keys=True))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    
    return JsonResponse(response)

# 获取创作者的文章记录
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
def article_list_by_name(request):
    response = {}
    try:
        page = request.GET.get('page')
        int(page)
        name_id = Creater.objects.filter(name=request.GET.get('name')).first()
        articles = Article.objects.filter(name_id=name_id.pk).order_by("-date_created")
        paginator = Paginator(articles, 6)
        article_list = paginator.page(page)
        response['list'] = json.loads(serializers.serialize("json",article_list,use_natural_foreign_keys=True))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = '到底了~'
        response['error_num'] = 1
    
    return JsonResponse(response)

# 获取指定id的文章
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
def article_by_id(request):
    response = {}
    try:
        id = request.GET.get('id')
        article = Article.objects.filter(id=id)
        response['list'] = json.loads(serializers.serialize("json",article,use_natural_foreign_keys=True))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    
    return JsonResponse(response)

# 搜索文章
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
def article_search(request):
    response = {}
    try:
        title = request.GET.get('title')
        print(title)
        article = Article.objects.filter(Q(title__icontains=title))
        response['list'] = json.loads(serializers.serialize("json",article,use_natural_foreign_keys=True))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    
    return JsonResponse(response)

# 创建文章
@require_http_methods(["POST"])
@method_decorator(csrf_exempt, name='dispatch')
@auth_permission_required()
def create_article(request):
    response = {}
    try:
        data = json.loads(request.body)
        category = Category.objects.get(name=data.get('category'))
        name = Creater.objects.get(name=data.get('name'))
        article = Article()
        article.title = data.get('title')
        article.content = data.get('content')
        article.cover_image = data.get('cover_image')
        article.category = category
        article.name = name
        article.save()
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)

# 更新文章
@require_http_methods(["POST"])
@method_decorator(csrf_exempt, name='dispatch')
@auth_permission_required()
def edit_article(request):
    response = {}
    try:
        data = json.loads(request.body)
        article_id = data.get('id')
        category = Category.objects.get(name=data.get('category'))
        name = Creater.objects.get(name=data.get('name'))
        title = data.get('title')
        content = data.get('content')
        cover_image = data.get('cover_image')
        Article.objects.filter(pk=article_id).update(name=name,category=category,title=title,content=content,cover_image=cover_image)
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)

# 點贊文章
@require_http_methods(["POST"])
@method_decorator(csrf_exempt, name='dispatch')
@auth_permission_required()
def like_article(request):
    response = {}
    try:
        data = json.loads(request.body)
        article_id = data.get('id')
        like = data.get('like')
        Article.objects.filter(pk=article_id).update(like=like)
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)

# 删除文章
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
@auth_permission_required()
def delete_article(request):
    response = {}
    try:
        id = request.GET.get('id')
        article = Article.objects.get(id=id)
        article.delete()
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)

# 关注
@require_http_methods(["POST"])
@method_decorator(csrf_exempt, name='dispatch')
@auth_permission_required()
def follow(request):
    response = {}
    try:
        data = json.loads(request.body)
        follow_name = Creater.objects.get(name=data.get('follow_name'))
        follow = Follow()
        follow.name = data.get('name')
        follow.follow_name = follow_name
        follow.save()
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)

# 获取某个人的关注列表
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
def follow_list(request):
    response = {}
    try:
        name = request.GET.get('name')
        follow = Follow.objects.filter(name = name)
        response['list'] = json.loads(serializers.serialize("json",follow,use_natural_foreign_keys=True))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    
    return JsonResponse(response)

# 取消关注
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
def cancel_follow(request):
    response = {}
    try:
        name = request.GET.get('name')
        follow_name = request.GET.get('follow_name')
        follow = Creater.objects.get(name = follow_name)
        follow_list = Follow.objects.get(name=name,follow_name_id = follow.pk)
        follow_list.delete()
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    
    return JsonResponse(response)

# 获取某个人的关注的文章
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
def follow_article(request):
    response = {}
    try:
        page = request.GET.get('page')
        int(page)
        name = request.GET.get('name')
        follow = Follow.objects.filter(name = name).values('follow_name_id')
        print(follow)
        article = Article.objects.filter(name_id__in=follow).order_by("-date_created")
        paginator = Paginator(article, 6)
        article_list = paginator.page(page)
        response['list'] = json.loads(serializers.serialize("json",article_list,use_natural_foreign_keys=True))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = '已经到底了~'
        response['error_num'] = 1
    
    return JsonResponse(response)

# 检测是否关注
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
def check_follow(request):
    response = {}
    try:
        name = request.GET.get('name')
        follow_name = Creater.objects.filter(name = request.GET.get('follow_name')).first()
        print(follow_name.pk)
        follow = Follow.objects.filter(name = name,follow_name = follow_name.pk).first()
        response['check'] = False
        if(follow):
            response['check'] = True
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    
    return JsonResponse(response)

# 获取用户信息
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
@auth_permission_required()
def user_profile(request):
    response = {}
    try:
        username = request.GET.get('username')
        user = Creater.objects.filter(name = username)
        response['list'] = json.loads(serializers.serialize("json",user))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    
    return JsonResponse(response)

# 获取创作者信息
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
def creater_profile(request):
    response = {}
    try:
        username = request.GET.get('username')
        user = Creater.objects.filter(name = username)
        data = json.loads(serializers.serialize("json",user))
        print(data)
        response['list'] = json.loads(serializers.serialize("json",user, fields=('name', 'profile_pic')))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    
    return JsonResponse(response)

# 创建评论
@require_http_methods(["POST"])
@method_decorator(csrf_exempt, name='dispatch')
@auth_permission_required()
def comment(request):
    response = {}
    try:
        data = json.loads(request.body)
        article = Article.objects.get(id=data.get('article_id'))
        name = Creater.objects.get(name=data.get('name'))
        comment = Comment()
        comment.content = data.get('content')
        comment.article = article
        comment.name = name
        comment.save()
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)

# 获取指定id的评论
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
def comment_by_id(request):
    response = {}
    try:
        id = request.GET.get('id')
        article = Article.objects.get(id=id)
        comment = Comment.objects.filter(article_id=article.pk)
        response['list'] = json.loads(serializers.serialize("json",comment,use_natural_foreign_keys=True))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    
    return JsonResponse(response)

# 删除评论
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
@auth_permission_required()
def delete_comment(request):
    response = {}
    try:
        id = request.GET.get('id')
        comment = Comment.objects.get(id=id)
        comment.delete()
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)

# 获取创作者的评论记录
@require_http_methods(["GET"])
@method_decorator(csrf_exempt, name='dispatch')
def comment_list_by_name(request):
    response = {}
    try:
        page = request.GET.get('page')
        int(page)
        name_id = Creater.objects.filter(name=request.GET.get('name')).first()
        comments = Comment.objects.filter(name_id=name_id.pk)
        paginator = Paginator(comments, 8)
        comment_list = paginator.page(page)
        response['list'] = json.loads(serializers.serialize("json",comment_list,use_natural_foreign_keys=True))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = '到底了~'
        response['error_num'] = 1
    
    return JsonResponse(response)

# 注册
@require_http_methods(["POST"])
@method_decorator(csrf_exempt, name='dispatch')
def register(request):
    response = {}
    try:
        data = json.loads(request.body)
        user_obj = Creater.objects.filter(name=data.get('name')).first()
        if user_obj:
            response['msg'] = '该用户名已被注册'
            response['error_num'] = 1
            return JsonResponse(response)
        creater = Creater()
        creater.name = data.get('name')
        creater.password = data.get('password')
        creater.profile_pic = '/images/other.jpg'
        creater.save()
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)

# 保存用户信息（不含密码）
@require_http_methods(["POST"])
@method_decorator(csrf_exempt, name='dispatch')
@auth_permission_required()
def save_userinfo(request):
    response = {}
    try:
        data = json.loads(request.body)
        user_obj = Creater.objects.filter(name=data.get('old_name')).first()
        print(user_obj.pk)
        Creater.objects.filter(pk=user_obj.pk).update(name=data.get('name'),profile_pic=data.get('profile_pic'))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)

# 保存用户密码
@require_http_methods(["POST"])
@method_decorator(csrf_exempt, name='dispatch')
@auth_permission_required()
def save_password(request):
    response = {}
    try:
        data = json.loads(request.body)
        pwd = hashlib.sha1(data.get('old_password').encode('utf-8')).hexdigest()
        user_obj = Creater.objects.filter(name=data.get('name'),password=pwd).first()
        if(user_obj):
            new_pwd = hashlib.sha1(data.get('new_password').encode('utf-8')).hexdigest()
            Creater.objects.filter(pk=user_obj.pk).update(password=new_pwd)
        else:
            response['error_num'] = 1
            response['msg'] = '原密码错误'
            return JsonResponse(response)
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1

    return JsonResponse(response)

# 上传图片
@require_http_methods(["POST"])
@method_decorator(csrf_exempt, name='dispatch')
def uploads(request):
    response = {}
    try:
        form = Images(image=request.FILES.get('pic'))
        form.save()
        response['msg'] = 'http://127.0.0.1:8000/images/'+str(form.image)
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)

# 登录获取token
@require_http_methods(["POST"])
@method_decorator(csrf_exempt, name='dispatch')
def login(request):
    response = {}
    try:
        data = json.loads(request.body)
        user = data.get('username')
        pwd = hashlib.sha1(data.get('password').encode('utf-8')).hexdigest()
        print(pwd)
        print(user)
        user_obj = Creater.objects.filter(name=user,password=pwd).first()
        print(user_obj)
        if not user_obj:
            response['msg'] = '用户账户或密码错误'
            response['error_num'] = 1
            return JsonResponse(response)
        token = create_token({'username': user})
        Creater.objects.filter(name=user,password=pwd).update(token = token)
        response['token'] = token
        response['msg'] = 'SUCCESS'
        response['error_num'] = 0          
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)